<?php

namespace Post\Model;

use Carbon\Carbon;
use Common\Model\BaseModel;
use Biz\AliyunLive;
use Common\Model\ModelException;

class PostReplyModel extends BaseModel
{
    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
        ['create_ip', 'get_client_ip', self::MODEL_INSERT, 'function'],
        ['contents', 'replaceBadWord', self::MODEL_BOTH, 'callback'],
    ];

    protected $_validate = [
        ['contents', 'require', '内容不能为空'],
        ['user_id', 'require', '发布人不能为空'],
    ];

    protected $_scope = [
        'valid' => [
            'where' => ['audit' => 1, 'delete_time' => 0],
        ],
    ];

    protected function _after_find(&$record, $options)
    {
        Carbon::setLocale('zh');
        $user = get_user();
        $zanIds = D('ReplyZan')->where(['user_id' => $user['id']])->getField('reply_id', true);
        $record['is_zan'] = in_array($record['reply_id'], $zanIds) ? 1 : 0;
        $record['human_time'] = Carbon::createFromTimestamp($record['create_time'])->diffForHumans();
    }

    protected function _after_select(&$records, $options)
    {
        $user = get_user();
        $zanIds = D('ReplyZan')->where(['user_id' => $user['id']])->getField('reply_id', true);
        Carbon::setLocale('zh');
        foreach ($records as &$record) {
            $record['is_zan'] = in_array($record['reply_id'], $zanIds) ? 1 : 0;
            $record['human_time'] = Carbon::createFromTimestamp($record['create_time'])->diffForHumans();
        }
    }

    /**
     * 过滤敏感词
     * @param string $data
     * @return string
     */
    protected function replaceBadWord($data)
    {
        // 因为后台管理与API不在同一项目，故不能使用缓存
        $v = unserialize(D('Setting')->getByK('articlesensitivewords')['v']);
        $words = empty($v['word']) ? [] : explode('|', trim($v['word'], '|'));
        return filter_badwords($data, $words);
    }
}
